﻿import { Toast } from 'vant'
var mts = {
    moneyStr: function(x, length) {
        if (isNaN(x)) return x;
        var x = x || 0;
        length = length || 2;
        if (x == undefined) return;
        if (x.toString().lastIndexOf('.') == -1) {
            var f = x;
        } else {
            var f = x.toString().substring(0, x.toString().lastIndexOf('.') + length + 1);
        }
        var s = f.toString();
        var rs = s.indexOf('.');
        if (rs < 0) {
            rs = s.length;
            s += '.';
        }
        while (s.length <= rs + length) {
            s += '0';
        }
        return s;
    },
    copy: function(type) {
        var str = type;
        var copy = document.getElementById(str);
        console.log(copy)
        if (document.body.createTextRange) {
            var range = document.body.createTextRange();
            range.moveToElementText(copy);
            range.select();
        } else if (window.getSelection) {
            var selection = window.getSelection();
            var range = document.createRange();
            range.selectNodeContents(copy);
            selection.removeAllRanges();
            selection.addRange(range);
        }
        document.execCommand('Copy');
        Toast({ message: "复制成功", duration: 1600 });
    },
    // 图片转base64
    base: function(file, backData) {
        /*
         * file:input上传图片
         * backData：处理完成回调函数
         * */
        // 通过构造函数初始化一个FileReader对象
        // FileReader 对象允许Web应用程序异步读取存储在用户计算机上的文件（或原始数据缓冲区）的内容
        var reader = new FileReader();
        // 使用new Image()进行预加载
        var image = new Image();
        var _this = this;
        var canvas = this.createCanvas();
        var ctx = canvas.getContext("2d");
        reader.onload = function() {
            // 文件加载完处理
            var result = this.result;
            image.onload = function() {
                // 图片加载完处理
                var imgScale = _this.imgScaleW(350, this.width, this.height);
                canvas.width = imgScale.width;
                canvas.height = imgScale.height;
                ctx.drawImage(image, 0, 0, imgScale.width, imgScale.height);
                var dataURL = canvas.toDataURL("image/jpeg"); // 图片base64
                ctx.clearRect(0, 0, imgScale.width, imgScale.height); // 清除画布
                backData(dataURL, file.name); //dataURL:处理成功返回的图片base64
            };
            image.src = result;
        };
        reader.readAsDataURL(file);
    },
    // 创建画布
    createCanvas: function() {
        // 创建画布
        var canvas = document.getElementById("canvas");
        if (!canvas) {
            var canvasTag = document.createElement("canvas");
            canvasTag.setAttribute("id", "canvas");
            canvasTag.setAttribute("style", "display:none;"); //隐藏画布
            document.body.appendChild(canvasTag);
            canvas = document.getElementById("canvas");
        }
        return canvas;
    },
    //去除字符串和数字首尾的空格
    hfWhite: function(str) {
        if (typeof(str) == "string" || typeof(str) == "number") {
            return str.toString().replace(/(^\s*)|(\s*$)/g, "");
        } else {
            return str;
        }
    },
    accAdd: function(arg1, arg2) { //加法
        var r1, r2, m, n;
        try { r1 = arg1.toString().split(".")[1].length } catch (e) { r1 = 0 }
        try { r2 = arg2.toString().split(".")[1].length } catch (e) { r2 = 0 }
        m = Math.pow(10, Math.max(r1, r2))
        n = (r1 >= r2) ? r1 : r2;
        return Number(((arg1 * m + arg2 * m) / m).toFixed(n));

    },

    //减法
    Subtr: function(arg1, arg2) {
        var r1, r2, m, n;
        try { r1 = arg1.toString().split(".")[1].length } catch (e) { r1 = 0 }
        try { r2 = arg2.toString().split(".")[1].length } catch (e) { r2 = 0 }
        m = Math.pow(10, Math.max(r1, r2));
        n = (r1 >= r2) ? r1 : r2;
        return Number(((arg1 * m - arg2 * m) / m).toFixed(n));
    },
    accMul: function(arg1, arg2) {
        var m = 0,
            s1 = arg1.toString(),
            s2 = arg2.toString();
        try { m += s1.split(".")[1].length } catch (e) {}
        try { m += s2.split(".")[1].length } catch (e) {}
        return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m)
    },
    accDiv: function(arg1, arg2) { //除法
        var t1 = 0,
            t2 = 0,
            r1, r2;
        try { t1 = arg1.toString().split(".")[1].length } catch (e) {}
        try { t2 = arg2.toString().split(".")[1].length } catch (e) {}
        r1 = Number(arg1.toString().replace(".", ""))
        r2 = Number(arg2.toString().replace(".", ""))
        return (r1 / r2) * Math.pow(10, t2 - t1);
    },
    // 图片压缩
    imgScaleW: function(maxWidth, width, height) {
        /* maxWidth:宽度或者高度最大值
         * width：宽度
         * height：高度
         * */
        var imgScale = {};
        var w = 0;
        var h = 0;
        if (width <= maxWidth && height <= maxWidth) {
            // 如果图片宽高都小于限制的最大值,不用缩放
            imgScale = {
                width: width,
                height: height
            };
        } else {
            if (width >= height) {
                // 如果图片宽大于高
                w = maxWidth;
                h = Math.ceil((maxWidth * height) / width);
            } else {
                // 如果图片高大于宽
                h = maxWidth;
                w = Math.ceil((maxWidth * width) / height);
            }
            imgScale = {
                width: w,
                height: h
            };
        }
        return imgScale;
    },
    // 复制功能 文本
    copyUrl: function(type, copyMsg) {
        var copy = document.getElementById(type);
        console.log(copy);
        if (document.body.createTextRange) {
            var range = document.body.createTextRange();
            range.moveToElementText(copy);
            range.select();
        } else if (window.getSelection) {
            var selection = window.getSelection();
            selection.removeAllRanges();
            var range = document.createRange();
            range.selectNodeContents(copy);
            selection.addRange(range);
            document.execCommand("Copy");
            selection.removeAllRanges();
        }
        if (copyMsg) {
            this.openCopyMsg(copyMsg);
        } else {
            Toast({ message: '复制成功', duration: 1600 });
        }
    },
    dataURLtoFile: function(dataurl, fileName) {
        var arr = dataurl.split(',');
        var mime = arr[0].match(/:(.*?);/)[1];
        var bstr = atob(arr[1]);
        var n = bstr.length;
        var u8arr = new Uint8Array(n);
        while (n--) {
            u8arr[n] = bstr.charCodeAt(n);
        }
        //转换成file对象
        return new File([u8arr], fileName, { type: mime });
        //转换成成blob对象
        //return new Blob([u8arr],{type:mime});
    },
    openCopyMsg: function(dom) {
        var ele = document.getElementById(dom);
        ele.style.display = "block";
        // this.showInfo=true;
        setTimeout(function() {
            ele.style.display = "none";
        }, 500);
    },
    // 函数防抖动
    debounce: function(fn, delay) {
        if (window.debounceTimer) clearTimeout(window.debounceTimer);
        var context = this;
        var args = arguments;
        window.debounceTimer = setTimeout(function() {
            fn.apply(context, args)
        }, delay)
    },
    //获取字符串中某个字符第几次出现的位置
    find: function(str, cha, num) {
        var x = str.indexOf(cha);
        for (var i = 0; i < num; i++) {
            x = str.indexOf(cha, x + 1);
        }
        return x;
    },
    setCookie: function(c_name, value, expiredays) {
        var exdate = new Date();
        exdate.setMinutes(exdate.getMinutes() + expiredays)
            // console.log(exdate.setMinutes(exdate.getMinutes()+expiredays));
            // console.log(exdate);
            // console.log(exdate.toGMTString());
        document.cookie = c_name + "=" + escape(value) + ((expiredays == null) ? "" : ";expires=" + exdate.toUTCString())
    },
    getCookie: function(c_name) {
        if (document.cookie.length > 0) {
            var c_start = document.cookie.indexOf(c_name + "=")
            if (c_start != -1) {
                c_start = c_start + c_name.length + 1
                var c_end = document.cookie.indexOf(";", c_start)
                if (c_end == -1) c_end = document.cookie.length
                return unescape(document.cookie.substring(c_start, c_end))
            }
        }
        return ""
    },
    //格式化时间
    dateFormat(fmt, date) {
        let ret;
        const opt = {
            "Y+": date.getFullYear().toString(), // 年
            "m+": (date.getMonth() + 1).toString(), // 月
            "d+": date.getDate().toString(), // 日
            "H+": date.getHours().toString(), // 时
            "M+": date.getMinutes().toString(), // 分
            "S+": date.getSeconds().toString() // 秒
                // 有其他格式化字符需求可以继续添加，必须转化成字符串
        };
        for (let k in opt) {
            ret = new RegExp("(" + k + ")").exec(fmt);
            if (ret) {
                fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
            };
        };
        return fmt;
    },
    //用法 let date = new Date()
    // dateFormat("YYYY-mm-dd HH:MM", date)
    // >>> 2019-06-06 19:45`

    // goLogin:function(n,p){
    //   console.log(this)
    // },
    //登录
    Glogin: function(u, p, m) {
        var that = this;
        console.log("这是登录");
        u = that.hfWhite(u);
        p = that.hfWhite(p);
        console.log(u, p);
        that.$axios.post("/fhApHome/login", {
            userName: u,
            password: p
        }).then(res => {
            console.log("登录接口");
            console.log(m)
            console.log(res);
            if (res.data.ok) {
                var enU = that.base64.encode(u)
                var enP = that.base64.encode(p);
                that.setCookie("uName", enU, 480); //存用户名，和密码，保存1个小时
                that.setCookie("pwd", enP, 480);
                localStorage.setItem('user', u)
                if (res.data.code == '0') {
                    console.log("code=0,登录成功")
                    that.$store.commit("changeToken", true);
                    console.log(res.data.registerId)
                    that.$store.commit("changerefId", res.data.registerId);
                    that.$store.commit('changeUsdtAddr', res.data.usdtAddr)
                    console.log("查看token的状态");
                    console.log(this.$store.state.token)
                    that.socket();
                    if (m) {
                        if (that.$route.path == '/login') {
                            that.$router.push('/index');
                        }
                    } else {
                        that.$router.push('/index');
                    }
                }
                if (res.data.code == '1') {
                    console.log("code=1,需要手机号验证");
                    that.$router.push('/firstLogin');
                }
                if (res.data.code == '2') {
                    console.log("code=2")
                    console.log("code=1,首次登录需要改密码");
                    that.$router.push('/firstPwd');
                }
            } else {
                console.log(res.data.msg);
                if (m) {

                } else {
                    that.$store.commit("changeLoginErrorFlag", true);
                    that.$store.commit("changeLoginError", res.data.msg);
                }
            }
        })

    },
    /***滑动限制***/
    stop() {
        var mo = function(e) {
            e.preventDefault();
        };
        document.body.style.overflow = "hidden";
        document.addEventListener("touchmove", mo, false); //禁止页面滑动
    },
    /***取消滑动限制***/
    move() {
        var mo = function(e) {
            e.preventDefault();
        };
        document.body.style.overflow = ""; //出现滚动条
        document.removeEventListener("touchmove", mo, false);
    },
    moneyStr: function(x, length) {
        if (isNaN(x)) return x;
        var x = x || 0;
        length = length || 2;
        if (x == undefined) return;
        if (x.toString().lastIndexOf('.') == -1) {
            var f = x;
        } else {
            var f = x.toString().substring(0, x.toString().lastIndexOf('.') + length + 1);
        }
        var s = f.toString();
        var rs = s.indexOf('.');
        if (rs < 0) {
            rs = s.length;
            s += '.';
        }
        while (s.length <= rs + length) {
            s += '0';
        }
        return s;
    },
}
const MyPlugin = {
    install: function(Vue, options) {
        for (var key in mts) {
            Vue.prototype[key] = mts[key]
        }
    }
};
export default MyPlugin